//
//  YQUserAccountViewModel.m
//  WeiboOC
//
//  Created by yang on 15/11/15.
//  Copyright © 2015年 yang. All rights reserved.
//

#import "YQUserAccountViewModel.h"

@implementation YQUserAccountViewModel
- (YQUserAccount*)account
{
    YQUserAccount* user = [[YQUserAccount alloc] init];
    return [user loadAccount];
}
- (BOOL)userLogin
{
    return self.account.access_token != nil;
}
- (NSString*)tooken
{
    return self.account.access_token;
}
- (NSString*)userName
{
    return self.account.name;
}
- (NSURL*)userHeadURL
{
    if (self.account.avatar_large != nil) {
       return [NSURL URLWithString:self.account.avatar_large];
    }
    return nil;
}
//获取授权过的Access Token(POST)
- (void)loadAccessToken:(NSString*)code finished:(finished)finished
{
    NSString* urlString = @"oauth2/access_token";
    NSDictionary* parameters = @{ @"client_id" : client_id,
        @"client_secret" : client_secret,
        @"grant_type" : @"authorization_code",
        @"code" : code,
        @"redirect_uri" : redirect_uri };
    [[YQNetworkTools sharedTools] requestJsonDict:POST urlString:urlString parameters:parameters finished:^(id dict, NSError *error) {
        YQUserAccount* userAccount = [YQUserAccount userAccountWithDict:dict];
        [self loadUserInfo:userAccount finished:finished];
    }];
}
//获取用户信息(GET)
- (void)loadUserInfo:(YQUserAccount*)userAccount finished:(finished)finished
{
    NSString* urlString = @"2/users/show.json";
    NSDictionary* parameters = @{ @"access_token" : userAccount.access_token,
            @"uid" : userAccount.uid };
    [[YQNetworkTools sharedTools] requestJsonDict:GET urlString:urlString parameters:parameters finished:^(id dict, NSError *error) {
        userAccount.avatar_large = dict[@"avatar_large"];
        userAccount.name = dict[@"name"];
        [userAccount saveAccount];
        finished(nil);
    }];
}
@end
